<template>
  <div class="main-box">
    <div class="head">

      <el-upload enctype="multipart/form-data" class="avatar-uploader" action="http://localhost:8080/upload/avatar"
        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
        :data="uploadData">
        <img v-if="imageUrl" :src="imageUrl" class="avatar user" />
      </el-upload>

    </div>
    <div class="bottom">
      <div class="userm">
        <h4>用户信息</h4>
        <ul title="用户信息">
          <li>用户名: {{ activeData.nickName }}</li>
          <li>姓名:{{ activeData.realName }}</li>
          <li>性别:{{ activeData.sex }}</li>
          <li>电话:{{ activeData.teleNumber }}</li>
          <li>Email:{{ activeData.email }}</li>
        </ul>
      </div>

      <div>
        <el-dialog v-model="isShow" :title="status === 0 ? '添加用户' : '编辑用户'" v-loading="isLoading">
          <el-form :model="activeData" inline :rules="rules" ref="formRef">
            <!-- <el-form-item label="ID" prop="id">
          <el-input placeholder="请输入ID" v-model.number="activeData.id" autocomplete="off" disabled />
        </el-form-item> -->
            <el-form-item label="用户名" prop="nickName">
              <el-input placeholder="请输入用户名" v-model="activeData.nickName" autocomplete="off" />
            </el-form-item>
            <!-- <el-form-item label="密码" prop="password">
              <el-input placeholder="请输入密码" v-model="activeData.password" autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="姓名" prop="realName">
              <el-input placeholder="请输入姓名" v-model="activeData.realName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input placeholder="请输入邮箱" v-model="activeData.email" autocomplete="off" />
            </el-form-item>
            <!-- <el-form-item label="角色" prop="role">
              <el-radio-group v-model="activeData.role">
                <el-radio :label="0" size="large" border>普通用户</el-radio>
                <el-radio :label="1" size="large" border>管理员</el-radio>
              </el-radio-group>
            </el-form-item> -->

            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="activeData.sex">
                <el-radio :label="'男'" size="large" border>男</el-radio>
                <el-radio :label="'女'" size="large" border>女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电话" prop="teleNumber">
              <el-input placeholder="请输入电话" v-model="activeData.teleNumber" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="isShow = false">取消</el-button>
              <el-button type="primary" @click="dialogConfirm(formRef)">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>

      <div class="btn">
        <el-button @click="editUser(user)" type="primary" plain>修改个人信息</el-button>
        <el-button @click="submit()" type="primary" plain>修改密码</el-button>
      </div>
    </div>
  </div>
</template>


<script lang="ts">
import view from '../../util/view'
import { defineComponent, ref, reactive, toRefs } from "vue";
import { useRouter } from 'vue-router'
import { baseUrl } from '../../types/baseUrl'
import { ElMessage, UploadProps, FormInstance } from 'element-plus'
import { getOne } from '../../http/api'
import { InitData, UserInfoListInt } from '@/types/admin/userInfo';
import {
  editOneUser,
} from '@/http/adminApi';

export default defineComponent({
  setup() {
    const data = reactive(new InitData());
    const editUser = (row: UserInfoListInt) => {
      // 编辑用户
      data.status = 1;
      data.activeData = JSON.parse(JSON.stringify(row));
      data.activeDataPointer = row;
      data.isShow = true;
    };

    const dialogConfirm = (formRef: FormInstance) => {
      formRef.validate((valid) => {
        if (valid) {
          data.isLoading = true;
          if (data.status === 1) {
            // console.log('edit');
            editOneUser(data.activeData)
              .then((res) => {
                if (res.data.code == 200) {
                  ElMessage.success('修改成功');
                  for (let key in data.activeData)
                    data.activeDataPointer[key] = data.activeData[key];
                  data.isLoading = false;
                  data.isShow = false;
                  //  updateList();
                  localStorage.setItem('user', JSON.stringify(data.activeData))
                }
                else {
                  ElMessage.error(res.data.msg);
                }

              })
              .catch(() => {
                ElMessage.error('修改失败');
                data.isLoading = false;
              });
          }
        } else {
          ElMessage.error('内容有错误！');
        }
      });
      data.isShow = false;
    };

    const rules = {
      role: [{ required: true, message: '请选择身份' }],
      nickName: [
        { required: true, message: '请输入用户名' },
        { min: 4, max: 15, message: '账号长度需要介于4-15', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码' },
        { min: 6, max: 18, message: '密码长度需要介于6-18', trigger: 'blur' },
      ],
    };

    const mixins = [view]
    const router = useRouter()
    const submit = () => {
      router.push('/userchange')
    }
    const user = JSON.parse(localStorage.getItem("user"));
    // console.log(user);
    data.activeData = user
    const uploadData = {
      id: JSON.parse(localStorage.getItem("user")).id
    }

    const imageUrl = ref(baseUrl + "/" + user.avatar)
    // console.log(imageUrl);

    const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
      // console.log(response);

      imageUrl.value = URL.createObjectURL(uploadFile.raw!)
      ElMessage.success({
        message: '修改头像成功!',
        type: 'success'
      });
      getOne(uploadData).then(
        (res) => {
          // console.log(res);
          localStorage.setItem('user', JSON.stringify(res.data.user))
          location.reload();
        }
      ).catch(
        (err) => {
          // console.log(err);
        }
      )
      // console.log("s1");

    }

    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 8) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
      }
      // console.log(uploadData);
      return true
    }
    return {
      ...toRefs(data),
      user,
      submit,
      imageUrl,
      handleAvatarSuccess,
      beforeAvatarUpload,
      uploadData,
      mixins,
      rules,
      dialogConfirm,
      editUser
    };
  },
});
</script>


<style lang="scss" scoped>
.btn {
  margin-top: 6vh;
  height: 4.5vh;
  margin-left: 33vw;
}

.bottom {
  float: left;
}

h4 {
  margin-top: 4vh;
  margin-left: 7vw;
}

li {
  letter-spacing: 1vh;
  width: 50vw;
  margin-top: 3vh;
  margin-left: 7vw;
  list-style-type: none;
}

.main-box {
  justify-content: space-between;
  align-items: center;

  div::-webkit-scrollbar {
    width: 0;
  }

  overflow: auto;
  height: 91vh;
  width: 85vw;
  background-color: rgb(255, 255, 255);
  box-shadow: 0px 0px 1px 1px rgb(225, 222, 222);
}

.head {
  background-color: rgb(117, 178, 190);
  float: left;
  height: 39vh;
  width: 85vw;

  .user {
    margin-left: 34vw;
    margin-top: 3vh;
    border-radius: 50%;
    height: 30vh;
    width: 30vh;
    box-shadow: 0px 0px 1px 1px rgb(0, 0, 0);
    float: left;
  }
}
</style>
